package com.tenglong.teacher.ui.notiUtil;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.impl.customization.DefaultP2PSessionCustomization;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tenglong.teacher.MainActivity;
import com.tenglong.teacher.MyApplication;
import com.tenglong.teacher.R;
import com.tenglong.teacher.ui.answerq.chat.P2PChatActivity;
import com.tenglong.teacher.ui.port.MainCallback;
import com.tenglong.teacher.ui.utils.NimUtils;


import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class NotificationModule {
    public final static String NOTIFICATION_SESSIONID = "notification_sessionid";
    public final static String NOTIFICATION_ACCID = "notification_accid";
    public static final int NOTIFICATION_VERIFY_MESSAGE = 2;
    public static final int NOTIFICATION_HOMEWORK = 1;
    public static final long HOMEWORK_WAITTIME = 1000;

    public static final String KEY_SKIP_ACTIVITY_TYPE = "key_skip_activity_type";

    private Context mContext;
    private MsgServiceObserve nimMsgService;
    private MyHandler mHandler;
    public Queue<HomeWorkNotification> mHomeWorkQueue;

    public class HomeWorkNotification {
        public long addtime;
        public IMMessage msg;
    }

    //通知相关
    private Observer<List<IMMessage>> messageReceiverObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> imMessages) {
            if (imMessages != null) {
                for (IMMessage imMessage : imMessages) {
                    sendNotification(imMessage);
                }
            }
        }
    };


    public NotificationModule(Context context) {
        this.mContext = context;
        mHomeWorkQueue = new LinkedList<HomeWorkNotification>();
        mHandler = new MyHandler(this);
    }


    public void registerNotificationObserver() {
        if (nimMsgService == null) {
            nimMsgService = NIMClient.getService(MsgServiceObserve.class);
        }
        nimMsgService.observeReceiveMessage(messageReceiverObserver, true);
    }

    public void unRegisterNotificationObserver() {
        if (nimMsgService == null) {
            nimMsgService = NIMClient.getService(MsgServiceObserve.class);
        }
        nimMsgService.observeReceiveMessage(null, true);
    }


    private void sendNotification(IMMessage imMessage) {
        if (imMessage.getDirect() == MsgDirectionEnum.Out) return;
        if (NimUtils.getMsgType(imMessage) == NimUtils.HOMEWORK_TYPE) {
            //作业逻辑在这里实现
            if (mHomeWorkQueue.size() > 0) {
                for (HomeWorkNotification m : mHomeWorkQueue) {
                    if (NimUtils.getMsgSessionId(imMessage).equals(NimUtils.getMsgSessionId(m.msg))) {
                        return;
                    }
                }
                long time = SystemClock.currentThreadTimeMillis();
                HomeWorkNotification hn = new HomeWorkNotification();
                hn.addtime = time;
                hn.msg = imMessage;
                mHomeWorkQueue.offer(hn);
            } else {
                long time = SystemClock.currentThreadTimeMillis();
                HomeWorkNotification hn = new HomeWorkNotification();
                hn.addtime = time;
                hn.msg = imMessage;
                mHomeWorkQueue.offer(hn);
                Message message = new Message();
                message.what = NOTIFICATION_HOMEWORK;
                mHandler.sendMessageDelayed(message, HOMEWORK_WAITTIME);
            }
        } else if (NimUtils.getMsgType(imMessage) == NimUtils.ANSWER_QESTION_TYPE) {
            int notificationId = 0;
            String ticker = "ticker";
            String subText = "答疑";
            String contentTitle = "答疑";
            String contentText = "您收到学生的答疑消息，请点击查看";
            Intent intent = new Intent(mContext, P2PChatActivity.class);
            intent.putExtra(Extras.KEY_SE_ID, NimUtils.getMsgSessionId(imMessage));
            intent.putExtra(Extras.EXTRA_ACCOUNT, imMessage.getSessionId());
            intent.putExtra(Extras.EXTRA_CUSTOMIZATION, new DefaultP2PSessionCustomization());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            getNotificationUtils(NimUtils.ANSWER_QESTION_TYPE).notifyMessage(notificationId, pendingIntent,
                    R.mipmap.ic_launcher, R.mipmap.ic_launcher, ticker, subText, contentTitle, contentText, NotificationCompat.PRIORITY_HIGH, true, true, true);
        } else {
            int notificationId = 0;
            String ticker = "ticker";
            String subText = "班级信息";
            String contentTitle = "班级信息";
            String contentText = "您收到学生的加入班级请求";
            Intent intent = new Intent(mContext, MainActivity.class);
            intent.putExtra(KEY_SKIP_ACTIVITY_TYPE, NOTIFICATION_VERIFY_MESSAGE);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            getNotificationUtils(NimUtils.ANSWER_QESTION_TYPE).notifyMessage(notificationId, pendingIntent,
                    R.mipmap.ic_launcher, R.mipmap.ic_launcher, ticker, subText, contentTitle, contentText, NotificationCompat.PRIORITY_HIGH, true, true, true);
            Activity listener = MyApplication.mActivityManage.findActivity(MainActivity.class);
            if (listener!=null){
                ((MainCallback)listener).onUserRefresh();
            }
        }
    }

    public NotificationUtils getNotificationUtils(int type) {
        NotificationUtils notificationUtils = null;
        if (type == NimUtils.ANSWER_QESTION_TYPE) {
            NotificationUtils.ChannelBuilder channelBuilder = new NotificationUtils.ChannelBuilder("aq", "aq", "answerquestion", NotificationManager.IMPORTANCE_DEFAULT)
                    .setChannelName("答疑")
                    .setByPassDnd(true) //是否绕过免打扰
                    .setShowBadge(false) //是否在桌面显示未读消息数量
                    .setEnableLight(true) //是否需要显示指示灯
                    .setEnableSound(true) //是否开启铃声
                    .setEnableVibrate(true); //是否开启震动

            notificationUtils = new NotificationUtils(mContext, channelBuilder);
            notificationUtils.init("aq", "aq", "answerquestion", "answerquestion");
        } else if (type == NimUtils.HOMEWORK_TYPE) {
            NotificationUtils.ChannelBuilder channelBuilder = new NotificationUtils.ChannelBuilder("homework", "homework", "homework", NotificationManager.IMPORTANCE_DEFAULT)
                    .setChannelName("作业")
                    .setByPassDnd(true) //是否绕过免打扰
                    .setShowBadge(false) //是否在桌面显示未读消息数量
                    .setEnableLight(true) //是否需要显示指示灯
                    .setEnableSound(true) //是否开启铃声
                    .setEnableVibrate(true); //是否开启震动

            notificationUtils = new NotificationUtils(mContext, channelBuilder);
            notificationUtils.init("homework", "homework", "homework", "homework");
        } else {
            NotificationUtils.ChannelBuilder channelBuilder = new NotificationUtils.ChannelBuilder("addClass", "addClass", "addClass", NotificationManager.IMPORTANCE_DEFAULT)
                    .setChannelName("加入班级")
                    .setByPassDnd(true) //是否绕过免打扰
                    .setShowBadge(false) //是否在桌面显示未读消息数量
                    .setEnableLight(true) //是否需要显示指示灯
                    .setEnableSound(true) //是否开启铃声
                    .setEnableVibrate(true); //是否开启震动

            notificationUtils = new NotificationUtils(mContext, channelBuilder);
            notificationUtils.init("addClass", "addClass", "addClass", "addClass");
        }
        return notificationUtils;
    }

    public void sendRealHomeworkNotification(IMMessage msg) {
//        int notificationId = 0;
//        String ticker = "ticker";
//        String subText = "作业";
//        String contentTitle = "作业";
//        String contentText = "您收到学生的作业信息，请点击查看";
//        Intent intent =new Intent(mContext, HomeWorkDetailActivity.class);
//        intent.putExtra("sessionid",NimUtils.getMsgSessionId(msg));
//        intent.putExtra("type",NimUtils.HOMEWORK_TYPE);
//        intent.putExtra("title","作业");
//        intent.putExtra("accid",msg.getSessionId());


        int notificationId = 0;
        String ticker = "ticker";
        String subText = "作业";
        String contentTitle = "作业";
        String contentText = "您收到学生的作业信息，请点击查看";
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(KEY_SKIP_ACTIVITY_TYPE, NOTIFICATION_HOMEWORK);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        getNotificationUtils(NimUtils.HOMEWORK_TYPE).notifyMessage(notificationId, pendingIntent, R.mipmap.ic_launcher, R.mipmap.ic_launcher,
                ticker, subText, contentTitle, contentText, NotificationCompat.PRIORITY_HIGH, true, true, true);
        Activity listener = MyApplication.mActivityManage.findActivity(MainActivity.class);
        if (listener!=null){
            ((MainCallback)listener).onHomeworkRedPoint(true);
        }
    }


    private static class MyHandler extends Handler {

        private WeakReference<NotificationModule> mNotificationModlueWeak;

        public MyHandler(NotificationModule nm) {
            mNotificationModlueWeak = new WeakReference<NotificationModule>(nm);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            NotificationModule nm = mNotificationModlueWeak.get();
            switch (msg.what) {
                case NOTIFICATION_HOMEWORK:
                    HomeWorkNotification nimmsg = nm.mHomeWorkQueue.poll();
                    nm.sendRealHomeworkNotification(nimmsg.msg);
                    if (nm.mHomeWorkQueue.size() > 0) {
                        Message message = new Message();
                        message.what = NOTIFICATION_HOMEWORK;
                        HomeWorkNotification next = nm.mHomeWorkQueue.peek();
                        long minustime = next.addtime - nimmsg.addtime;
                        long time = HOMEWORK_WAITTIME;
                        if (minustime > 0) {
                            time = HOMEWORK_WAITTIME - minustime;
                        }
                        nm.mHandler.sendMessageDelayed(message, time);
                    }


            }
        }
    }

}
